//
//  BRWalletViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/9/25.
//  Copyright © 2021 Brezze GWG. All rights reserved.
// 钱包页面

#import "BRWalletViewController.h"
#import "BRAddCardViewController.h"
#import "BRTopUpHistoryViewController.h"
#import "BRWalletListCell.h"
#import "BRWalletBaseTCell.h"
#import "BRPaymentViewController.h"
#import "BRWalletHeadView.h"
#import "BRRefunedStatusViewController.h"

@interface BRWalletViewController ()<QMUITableViewDelegate,QMUITableViewDataSource>
{
    

}

@property (nonatomic,strong) BRWalletModel *walletModel;

@property (nonatomic,strong) BRWalletHeadView *headView;

@end

@implementation BRWalletViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    [self setUI];
    
    [self br_showHud:self.requireRentalConfigsType];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self requestWallet];
}

#pragma mark - Request --
- (void)requestWallet {
    
    [BRUserManager getWallet:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        self.tableView.hidden = NO;
        self.walletModel = [BRWalletModel mj_objectWithKeyValues:dataDict[@"data"]];
        [self.tableView reloadData];

        [self hiddAddBtn];
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        self.tableView.hidden = NO;
    }];
}

- (void)requestSetDefaut:(NSInteger)index isDefault:(BOOL)isDefault succ:(void(^)(void))succ fail:(void(^)(void))fail {
    [BRHud showInView:self.view];
    BRCardModel *model = self.walletModel.cardList[index];
    NSInteger isD = !isDefault ? 1 : 2;
    NSDictionary *params = @{@"id":model.cardId,@"type":@(isD)};
    [[BRRequestManager shared] PUT:[BRAPI defaultCard] params:params succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        [BRHud hiddenInView:self.view];

        if (succ) {
            succ();
        }
        model.defaulted = !isDefault ? 1 : 0;
        [self.tableView reloadData];


    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [BRHud hiddenInView:self.view];
        if (fail) {
            fail();
        }
    }];
}

- (void)requestDeleteCard:(NSInteger)index{
    
    BRCardModel *model = self.walletModel.cardList[index];

    NSString *cardId = model.cardId;

    [BRHud showInView:self.view];
    [[BRRequestManager shared] DELETE:[BRAPI deleteCard:cardId] params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {


        NSInteger result = [dataDict[@"data"][@"result"] integerValue];

        [BRHud hiddenInView:self.view];
        if (result == 0) {
            NSMutableArray *cardlist = [NSMutableArray arrayWithArray:self.walletModel.cardList];

            [cardlist removeObjectAtIndex:index];

            self.walletModel.cardList = cardlist;

            [self.tableView reloadData];

            if (cardlist.count == 0) {
                [self hiddAddBtn];
            }

            return;
        }
        [BRTools br_resultDo:dataDict text:@"Dialog_DeleteCard_Message" by:self];


    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {

        [BRHud hiddenInView:self.view];
    }];
}

- (void)requestRefund {
    [BRHud showInView:self.view];
    [[BRPayManager share] refundDeposit:^(NSDictionary * _Nonnull dic) {
        
        
        NSInteger result = [dic[@"data"][@"result"] integerValue];
        NSLog(@"dic = %@",dic);
        [BRHud hiddenInView:self.view];
        if (result == 0) {
            BRRefunedStatusViewController *vc = [[BRRefunedStatusViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
            return;
        }
        
        [BRTools br_resultDo:dic text:@"Dialog_Refund_Message" by:self];
       
        
    } faile:^{
        [BRHud hiddenInView:self.view];
    }];
}

#pragma mark - Action --
- (void)addCard {
    
    BRAddCardViewController *vc = [[BRAddCardViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)showCardSet:(NSInteger)index {
    
    WS(weakSelf);
    BRCustiomAlertView *alertV = [[BRCustiomAlertView alloc] initWithTitle:@"" subTitle:Localized(@"wallet_confirmRmCard") cancelStr:Localized(@"wallet_cancel") succStr:Localized(@"wallet_remove") cancelAction:^{
        
    } successAction:^{
        [weakSelf requestDeleteCard:index];
    } showBC:YES];
    
    [self.view addSubview:alertV];
    
}

- (void)hiddAddBtn {
    
    
    
}

- (void)toRecord {
    
    BRTopUpHistoryViewController *vc = [BRTopUpHistoryViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)toTopUp:(BOOL)isTopUp {
    if (!self.walletModel) return;
    
    if (!isTopUp) {
        BRPaymentViewController *payVC = [BRPaymentViewController new];
//        payVC.amount = self.walletModel.prepaymentAmount;
        payVC.amount = self.walletModel.requirePrepaymentAmount;
//        payVC.payType = BRPAY_Deposit;
        payVC.payType = BRPAY_PREAUTI;
        
        [self.navigationController pushViewController:payVC animated:YES];

    }else {
        WS(weakSelf);
        BRCustiomAlertView *alertV = [[BRCustiomAlertView alloc] initWithTitle:Localized(@"wallet_refund") subTitle:Localized(@"dialog_Refund_Message") cancelStr:Localized(@"public_notNow") succStr:Localized(@"public_confirm") cancelAction:^{
            
        } successAction:^{
            [weakSelf requestRefund];
        } showBC:YES];
        
        [self.view addSubview:alertV];
        
    }
}

- (void)itemClick:(UITapGestureRecognizer *)tap {
    

}

/// 根据类型展示弱提示 1展示通用 2 card、3 deposit、4 prepayment、5 apple_pay_token、6 google_pay_token
- (void)br_showHud:(NSInteger)type {
    if (type == 0) return;
    NSString *tips = Localized(@"wallet_tipsOneSel");
    
   
    [BRHud showTips:tips];
}


#pragma mark - CardSet delegate --
- (void)cardDelete:(NSInteger)index {
    
    
    [self requestDeleteCard:index];
    
}

- (void)cardSetDefault:(BOOL)isDefault index:(NSInteger)index {
    
    [self requestSetDefaut:index isDefault:isDefault succ:^{
        
    } fail:^{
        
    }];
}

#pragma mark - tableView Delegate --
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
//    return 2;隐藏预授权
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    
    if (section == 0 && self.walletModel.cardList.count != 0) {
        return self.walletModel.cardList.count;
    }
//    if (section == 0) {
//        return 0;
//    }
//
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return CGFLOAT_MIN;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return nil;
    }
    return [UIView new];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
//    return nil;
    
    UIView *sectionV = [[UIView alloc] init];
    NSString *text = section == 0 ? Localized(@"wallet_addBankCard") :Localized(@"wallet_depositTitle");
    QMUILabel *titleL = [BRToolsView br_label:text textColor:UIColor.qd_titleTextColor font:[UIFont fontS:17]];
    titleL.numberOfLines = 0;

    [sectionV addSubview:titleL];
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(26);
        make.right.offset(-10);
        make.centerY.offset(0);
        make.height.mas_greaterThanOrEqualTo(20);
    }];
    
    return sectionV;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
//    return CGFLOAT_MIN;
    
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSArray *cardList = self.walletModel.cardList;
    
    BOOL empty = cardList.count == 0;
    
    if (1 == indexPath.section) {
        
        BRWalletDepositTCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BRWalletDepositTCell"];
        if (!cell) {
            cell = [[BRWalletDepositTCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BRWalletDepositTCell"];
        }
        cell.isTopUp = self.walletModel.prepaymentAmount.floatValue > 0;
        
        cell.amountStr = [BRPayManager br_amount:self.walletModel.prepaymentAmount];
        
        WS(weakSelf);
        cell.btnClickBlock = ^(BOOL isTopup) {
            [weakSelf toTopUp:isTopup];
        };
        
        return cell;
    }
    
    if (empty) {
        BRWalletCardAddTCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BRWalletCardAddTCell"];
        if (!cell) {
            cell = [[BRWalletCardAddTCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BRWalletCardAddTCell"];
        }
        WS(weakSelf);
        cell.toSetBlock = ^{
            [weakSelf addCard];
        };
        return cell;
    }
    
    BRWalletCardTCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BRWalletCardTCell"];
    if (!cell) {
        cell = [[BRWalletCardTCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BRWalletCardTCell"];
    }
    
    cell.dto = self.walletModel.cardList[indexPath.row];
    WS(weakSelf);
    cell.toSetBlock = ^{
        [weakSelf showCardSet:indexPath.row];
    };
    
    return cell;
    
}


#pragma mark - SET UI --
- (void)setUI  {
    
    UIView *top = [self createTop:Localized(@"wallet_wallet") imageStr:@"arrow_left_white44"];
    top.backgroundColor = kColorMain;
    self.titleColor = UIColor.whiteColor;
    
    QMUIButton *rightBtn = [[QMUIButton alloc] init];
    [rightBtn setTitle:Localized(@"wallet_transactionRecord") forState:UIControlStateNormal];
    [rightBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont fontM:14];
    [top addSubview:rightBtn];
    [rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(kNavH);
        make.bottom.offset(0);
        make.right.offset(-28);
    }];
    [rightBtn addTarget:self action:@selector(toRecord) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *bgImg = [[UIImageView alloc] initWithImage:UIImageMake(@"wallet_bg")];
    [self.view addSubview:bgImg];
    [bgImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(kSafeAreaTopHeight);
        make.left.right.offset(0);
        
    }];
    
    self.tableView.estimatedRowHeight = UITableViewAutomaticDimension;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.frame = CGRectMake(0, kSafeAreaTopHeight, kScreenWidth, kScreenHeight - kSafeAreaTopHeight);
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[BRWalletListCell class] forCellReuseIdentifier:@"BRWalletListCell"];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.headView.frame = CGRectMake(0, 0, kScreenWidth, 290);
    self.tableView.tableHeaderView = self.headView;
    self.tableView.hidden = YES;
//    [self.view addSubview:self.setView];
}

- (BRWalletHeadView *)headView {
    
    if (_headView == nil) {
        _headView = [[BRWalletHeadView alloc] init];
    }
    return _headView;
}

- (BOOL)preferredNavigationBarHidden {
    return YES;
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
